﻿using System;
using System.Web;
using System.Text;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO; 
using MyLib;
 
namespace PerformanceReport.AjaxPage
{
    /// <summary>
    /// GenerateReports 的摘要说明
    /// </summary>
    public class GenerateAvgReports : IHttpHandler 
    {
        string strSql;
        string strJson;
        string strPara;
        string strStartDate;
        string strEndDate;
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            strPara = context.Request["Para"];             //流程名
            strStartDate = context.Request["StartDate"];     //开始时间
            strEndDate = context.Request["EndDate"];       //结束时间

            //string strSql = "Select  ProcessVersion,ProcessName,starttime,endtime,INCIDENT, "
            //                + "ROUND(TO_NUMBER(to_date(endtime) - to_date(starttime))) as Days"
            //                + "  from tasks";
            string strSql = " Select max(ProcessVersion) as Ver ,ProcessName, "         //得到最大的版本号（即最新版本号）
                              //+ "ROUND(avg(nvl(ROUND(TO_NUMBER(to_date(endtime) - to_date(starttime)))* 24 ,0)),2) as Hours"   //平均消耗（小时）,并且保留两位有效数字
                               + "ROUND(avg(ROUND(to_date(endtime) - to_date(starttime)))* 24 ,2) as Hours  "
                              + "  from Incidents";
            string where = " where 1=1 ";
            where += " and ProcessName like N'" + strPara.Trim() + "%'";
            if (!string.IsNullOrEmpty(strStartDate))
            {
                where += " and  starttime >= to_date('" + strStartDate.Trim() + "','yyyy-MM-dd')";
            }
            if (!string.IsNullOrEmpty(strEndDate))
            {
                where += " and  starttime <= to_date('" + strEndDate.Trim() + "','yyyy-MM-dd')";
            }

            //计算总天数
            //where += " and ROUND(TO_NUMBER(to_date(endtime) - to_date(starttime)))>(select avg(nvl(ROUND(TO_NUMBER(to_date(endtime) - to_date(starttime))),0)) from INCIDENTS)";
            //where += " order by ProcessName";
            where += "  group by ProcessName  order by ProcessName";
            string StrSqlTotal = strSql + where;
            DataTable dt = DataAccess.Instance("BizDB").ExecuteDataTable(StrSqlTotal.ToString());


            //如果存在返回值的情况
            if (dt.Rows.Count > 0)
            {
                //DataTable dtTemp = new DataTable();
                //dtTemp.Columns.Add("INCIDENT");
                //dtTemp.Columns.Add("ProcessName");
                //DataRow NewRow = dtTemp.NewRow();
                //NewRow["INCIDENT"] = dt.Rows[0]["INCIDENT"].ToString();
                //NewRow["ProcessName"] = dt.Rows[0]["ProcessName"].ToString();
                //dtTemp.Rows.Add(NewRow);

                //string strAvgDay = TotalAvgDay(dt);
                //string strAvgDay = AvgDay(dt);

                string strProcessName = InitProcessName(dt);
                string strAvgDay = ProcessAvgDay(dt, strPara);

                strJson = "[";

                //循环所有的行
                //for (int i = 0; i < dt.Rows.Count; i++)
                //{
                strJson += "{'ProcessName':'" + CheckText(strProcessName.Trim()) + "',"
                        + "'AvgDay':'" + CheckText(strAvgDay.Trim()) + "'},";
                
                //}
                strJson = strJson.Substring(0, strJson.LastIndexOf(','));
                strJson += "]";
            }

            context.Response.Buffer = true;
            context.Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
            context.Response.Expires = 0;
            context.Response.CacheControl = "no-cache";
            context.Response.Write(strJson);
        }

        //平均耗时
        public string TotalAvgDay(DataTable dt)
        {
            string strHtmlCount = string.Empty;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string strSql = "select  ProcessVersion,ProcessName,starttime,endtime,INCIDENT, "
                             + "ROUND(TO_NUMBER(to_date(endtime) - to_date(starttime))) as Days"
                             + " from INCIDENTS"
                             + " where ProcessName like N'%" + dt.Rows[i]["ProcessName"].ToString() + "%'"
                             + " and INCIDENT='" + dt.Rows[i]["INCIDENT"].ToString() + "'";
                             //+ " group by Steplabel,ProcessName,starttime,endtime";
                DataTable dtCount = DataAccess.Instance("BizDB").ExecuteDataTable(strSql.ToString());
                if (dtCount.Rows.Count > 0)
                {
                    for (int j = 0; j < dtCount.Rows.Count; j++)
                    {
                        //四舍五入,保留一位有效数字
                        if (dtCount.Rows[j]["Days"].ToString() != "")
                        {
                            dtCount.Compute("SUM([Days])", "true").ToString();
                            double Day = double.Parse(dtCount.Rows[j]["Days"].ToString());
                            double strAvgDay = Math.Round(Day, 1, MidpointRounding.AwayFromZero);
                            //int strAvgTime = int.Parse(dtCount.Rows[0]["times"].ToString()) / dtCount.Rows.Count;
                            strHtmlCount += strAvgDay + ",";
                        }
                    }
                }
                else
                {
                    strHtmlCount += "0" + ",";
                }
            }

            //拼接series值
            string strHeader = "{ type: 'column',name:'天'" + "," + "data:" + "[";  
            string strEnd = "]}";
            //string strStyle = ",marker: {lineWidth: 2, lineColor: Highcharts.getOptions().colors[3],fillColor: 'white'}}";
            string strTotal = strHeader + strHtmlCount.TrimEnd(',') + strEnd;         
            return strTotal;
            //return strHtmlCount.TrimEnd(',');
        }

        public string AvgDay(DataTable dt)
        {
            //拼接series值
            string strHeader = "{ type: 'column',name:'天'" + "," + "data:" + "[";
            string strEnd = "]}";
            //string strStyle = ",marker: {lineWidth: 2, lineColor: Highcharts.getOptions().colors[3],fillColor: 'white'}}";
            string strData = dt.Rows[0]["Days"].ToString();
            string strTotal = strHeader + strData + strEnd;
            return strTotal;
 
        }

        //流程名称
        public string InitProcessName(DataTable dt)
        {
            string strHtml = string.Empty;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                strHtml += dt.Rows[i]["ProcessName"].ToString().Trim() + ",";
            }
            return strHtml;        
        }

        //流程平均耗时
        public string ProcessAvgDay(DataTable dt, string strProcessName)
        {
            string strData = string.Empty;

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (dt.Rows[i]["Hours"].ToString() != "")
                {
                    //string strStyle = ",marker: {lineWidth: 2, lineColor: Highcharts.getOptions().colors[3],fillColor: 'white'}}";
                   // strData += GetAvgDay(dt.Rows[i]["Hours"].ToString()).Trim() + ",";  //2013-8-20注释
                    strData += GetAvgDay(dt.Rows[i]["Hours"].ToString(), strProcessName).Trim() + ",";
                }
                else
                {
                    strData += "0" + ",";
                }
            }

            //拼接series值
            string strHeader = "{ type: 'column',name:'平均天数'" + "," + "data:" + "[";
            string strEnd = "]}";
            string strTotal = strHeader + strData.TrimEnd(',') + strEnd;
            return strTotal;

        }
        //转换平均消耗（小时）为平均消耗（天）
        //public string GetAvgDay(string strHour)
        //{
        //    string strAvgDay = null;
        //    if (strHour != "")
        //    {
        //        double dDay = double.Parse(strHour);
        //        double dAvgDay = Math.Round(dDay / 24, 0, MidpointRounding.AwayFromZero);
        //        strAvgDay = dAvgDay.ToString();
        //    }
        //    return strAvgDay;

        //}
        public string GetAvgDay(string strHour, string strProcessName)
        {
            string strSq = "  select Round(SUM((endtime - starttime) * 24),2)/count(incident) as Hourss  from incidents where  ProcessName  like N'" + strProcessName.Trim() + "%' and status=2";
            DataTable dtsq = DataAccess.Instance("BizDB").ExecuteDataTable(strSq.ToString());
            string strAvgDay = null;
            if (dtsq.Rows.Count > 0)
            {
                double Horus = double.Parse(dtsq.Rows[0]["Hourss"].ToString());
                double dAvgDay = Math.Round(Horus, 0, MidpointRounding.AwayFromZero);
                strAvgDay = dAvgDay.ToString();
            }
            return strAvgDay;
        }

        public string CheckText(string Str)
        {
            string ReturnString = "";
            ReturnString = Str.Replace(",", "#dou#");
            ReturnString = Str.Replace("'", "#dan#");
            return ReturnString;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
         
    }
}